package com.hcc.flow.server.controller.sys;

import java.awt.image.BufferedImage;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
/*import javax.servlet.ServletOutputStream;*/
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.google.code.kaptcha.Producer;
import com.hcc.flow.server.common.utils.CommUtil;
import com.hcc.flow.server.service.sys.RedisServer;

/**
 * @author 韩长长 
 * @version createTime：2020年6月8日 下午6:59:41 验证码
 */

@RestController
@RequestMapping("/verify")
public class VerifyCodeController {

	@Autowired
	private Producer captchaProducer;

	@RequestMapping(value = "/getcode", method = RequestMethod.GET, produces = MediaType.IMAGE_JPEG_VALUE)
	public void getCaptcha(HttpServletResponse response,String isReg) throws IOException   {
		String uuid = CommUtil.uuid();
		// 将验证码key，及验证码的图片返回
		Cookie cookie = new Cookie("Y".equals(isReg)?"VerifyIdR":"VerifyId", uuid);
		cookie.setMaxAge(180);
		cookie.setPath("/");
		response.addCookie(cookie);
		response.setDateHeader("Expires", 0);
		// Set standard HTTP/1.1 no-cache headers.
		response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
		// Set IE extended HTTP/1.1 no-cache headers (use addHeader).
		response.addHeader("Cache-Control", "post-check=0, pre-check=0");
		// Set standard HTTP/1.0 no-cache header.
		response.setHeader("Pragma", "no-cache");
		// return a jpeg
		response.setContentType("image/jpeg");
	    // create the text for the image
	    String capText = captchaProducer.createText();
	    RedisServer.setCacheValue("login-code", uuid, capText, 360L);
	    // create the image with the text
	    BufferedImage bi = captchaProducer.createImage(capText);
	    //ByteArrayOutputStream bao = new ByteArrayOutputStream();
	    ServletOutputStream out = response.getOutputStream();
	    // write the data out
	    try {
	    	ImageIO.write(bi, "jpg", out); 
		    out.flush();  
		    //return bao.toByteArray();
	    } finally{
			out.close();
		}
	}
}
